package cn.dujc.superkid.activities;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.dujc.core.ui.BaseActivity;
import cn.dujc.core.util.ToastUtil;
import cn.dujc.superkid.R;
import cn.dujc.superkid.adapter.VipListAdapter;
import cn.dujc.superkid.api.HttpHelper;
import cn.dujc.superkid.api.QMap;
import cn.dujc.superkid.api.Result;
import cn.dujc.superkid.api.ResultCallBack;
import cn.dujc.superkid.bean.MemberVipResult;
import cn.dujc.superkid.bean.RegisterResult;
import cn.dujc.superkid.bean.VIPResult;
import cn.dujc.superkid.utils.Preferences;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class VipActivity extends BaseActivity implements View.OnClickListener {
    private final String TAG = VipActivity.class.getName();
    private TextView vipdata;
    private TextView btn_renewals;//    private TextView ll_answer_online;
    private RecyclerView vipRecyclerView;
    VipListAdapter vipListAdapter;
    @Override
    public int getViewId() {
        return R.layout.activity_vip;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        setTitle("会员中心");
        initView();
        loadVipList();
        loaddata();
        initOnClick();
        initBroadCast();
    }
    BroadcastReceiver broadcastReceiver;
    private void initBroadCast() {
        broadcastReceiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if(intent.getAction().equals("WxPaySuccess")){
                    loaddata();
                }
            }
        };
        IntentFilter filter=new IntentFilter("WxPaySuccess");
        registerReceiver(broadcastReceiver,filter);
    }
    private void initOnClick() {
//        findViewById(R.id.vip_kaitong_1).setOnClickListener(this); //月会员
//        findViewById(R.id.vip_kaitong_2).setOnClickListener(this);//半年会员
//        findViewById(R.id.vip_kaitong_3).setOnClickListener(this);//年会员
//        findViewById(R.id.vip_kaitong_4).setOnClickListener(this);//3月会员

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
    }

    private void initView() {
        vipdata = findViewById(R.id.vipdata);
        btn_renewals = findViewById(R.id.btn_renewals);
        vipRecyclerView=findViewById(R.id.vip_list_recycler);
        vipRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        vipListAdapter=new VipListAdapter(this);
        vipRecyclerView.setAdapter(vipListAdapter);
//        ll_answer_online = findViewById(R.id.ll_answer_online);

    }
    private void loadVipList(){
//        ?channel=1&logincode=AQNTAxgaUA1bBw4PWgRRAQ5NGVUNDARTAwYEDQM&time=1540778842&type_id=1&user_id=3413&token=1ad9f457c5a081566bfbd6978eedd45a
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
        HttpHelper.getHome().vip(QMap.build()
                .put("channel", Preferences.getInstance().getChannel(mActivity).getChannel_id())
                .put("user_id", Integer.parseInt(loginResult.getUid()))
                .put("logincode",loginResult.getLogincode())
                .put("type","2")
                .create()).enqueue(new Callback<Result<List<VIPResult>>>() {
            @Override
            public void onResponse(Call<Result<List<VIPResult>>> call, Response<Result<List<VIPResult>>> response) {
               vipListAdapter.setDatas(response.body().getData());
                vipRecyclerView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFailure(Call<Result<List<VIPResult>>> call, Throwable t) {

            }
        });
    }


    private void loaddata() {
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
        HttpHelper.getUserCenter().memberVip(QMap.build()
                .put("logincode", loginResult.getLogincode())
                .put("channel", Preferences.getInstance().getChannel(mActivity).getChannel_id())
                .put("user_id", Integer.parseInt(loginResult.getUid())).create()).enqueue(new ResultCallBack<Result<MemberVipResult>>(mActivity) {
            @Override
            public void onSuccessCallback(int code, Result<MemberVipResult> body) {
                if (body != null) {

                    String data = formatTimeInMillis(Long.parseLong(body.getData().getEnt_time()) * 1000);
                    long l = Long.parseLong(body.getData().getEnt_time()) * 1000;
                    final AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                    builder.setTitle("提示").setMessage("您还不是会员").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
//                             builder.di
                        }
                    }).setCancelable(true);
                    if (body.getData().getIs_vip().equals("1")) {
                        builder.show();
                    } else {
                        vipdata.setText("您的会员到期时间为" + data);
                    }
                    Date date = getNetTime();
                    long l2 = dateToLong(date);
                    Log.i(TAG, "==========caizhijia=logincodeEndtime===l2=========" + l2);
                    int Num = 3;

                    if ((l - l2) < (long) Num * 24 * 60 * 60 * 1000) {
                        btn_renewals.setVisibility(View.VISIBLE);
                        if (body.getData().getIs_vip().equals("1")) {
                            btn_renewals.setText("开通会员");
                        }
                    }
                }

            }
        });
    }

    public static String formatTimeInMillis(long timeInMillis) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(timeInMillis);
        Date date = cal.getTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        String dateFormatDate = dateFormat.format(date);

        return dateFormatDate;
    }

    public static long dateToLong(Date date) {
        return date.getTime();
    }

    public static Date getNetTime() {
        String webUrl = "http://www.ntsc.ac.cn";//中国科学院国家授时中心
        try {
            URL url = new URL(webUrl);
            URLConnection uc = url.openConnection();
            uc.setReadTimeout(5000);
            uc.setConnectTimeout(5000);
            uc.connect();
            long correctTime = uc.getDate();
            Date date = new Date(correctTime);
            return date;
        } catch (Exception e) {
            return new Date();
        }
    }


}
